package com.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(true);

        //获取配置的用户名和密码
        String username = this.getInitParameter("username");
        String password=this.getInitParameter("password");

        //没有配置用户名和密码
        if (username==null || password==null){
            req.setAttribute("message","服务器端账号密码信息有误，请联系管理员");
            req.setAttribute("requestURI",req.getContextPath()+"/login.html");
            req.getRequestDispatcher("/info.jsp").forward(req, resp);
            return;
        }

        //获取登录信息
        String submitUsername =req.getParameter("username");
        String submitPassword =req.getParameter("password");

        //未输入用户名和密码
        if (submitUsername==null ||submitPassword==null){
            req.setAttribute("message","请输入用户名和密码");
            req.setAttribute("requestURI",req.getContextPath()+"/login.html");
            req.getRequestDispatcher("/info.jsp").forward(req, resp);
            return;
        }

        //用户名和密码正确
        if (username.equals(submitUsername) && password.equals(submitPassword)){
            session.setAttribute("username",submitUsername);
            req.setAttribute("message","登录成功");
            req.setAttribute("requestURI",req.getContextPath()+"/index.html");
            req.getRequestDispatcher("/info.jsp").forward(req, resp);
            return;
        }

        //用户名和密码不正确
        req.setAttribute("message","用户名或密码错误请重新输入");
        req.setAttribute("requestURI",req.getContextPath()+"/login.html");
        req.getRequestDispatcher("/info.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
